<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name"  placeholder="请输入名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="spec">
              <a-input v-model="model.spec" disabled placeholder="请输入规格"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="公式" :labelCol="textareaLabelCol" :wrapperCol="textareaWrapperCol" prop="gs">
              <a-textarea v-model="model.gs" rows="4" placeholder="请输入公式" ref="textarea"  @blur="handleBlur" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-space wrap>
<!--              <a-button type="dashed" @click="fg('[')">[</a-button>-->
<!--              <a-button type="dashed" @click="fg(']')">]</a-button>-->
<!--              <a-button type="dashed" @click="fg('[')">[</a-button>-->
              <a-button type="dashed" @click="addPFB('[配方比]')">配方比</a-button>
              <a-button type="dashed" @click="selMat()">物料</a-button>
              <a-button type="dashed" @click="fg('(')">(</a-button>
              <a-button type="dashed" @click="fg(')')">)</a-button>
              <a-button type="dashed" @click="fg('+')">+</a-button>
              <a-button type="dashed" @click="fg('-')">-</a-button>
              <a-button type="dashed" @click="fg('*')">×</a-button>
              <a-button type="dashed" @click="fg('/')">÷</a-button>
              <a-button type="dashed" @click="clearGs()">清空</a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <erp-goods-list-model ref="selectGoodsList"
                          category="4"
                          @goodsOk="goodsOk">
    </erp-goods-list-model>
  </a-spin>
</template>

<script>

import {httpAction, postAction} from '@/api/manage'
import ErpGoodsListModel from "@comp/base/modal/ErpGoodsListModal";
export default {
  name: 'ErpGoodsFormulaGsForm',
  components: {ErpGoodsListModel},
  props: [{
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  }, "goods"],
  data() {
    return {
      model: {code: '', gs: '',materialId:'',gsMaterialId:''},
      cursorPosition:0,
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      textareaLabelCol: {
        xs: {span: 12},
        sm: {span: 2},
      },
      textareaWrapperCol: {
        xs: {span: 40},
        sm: {span: 21},
      },
      confirmLoading: false,
      validatorRules: {
        code: [
          {required: true, message: '请输入编号'}
        ],
        name: [
          {required: true, message: '请输入名称'}
        ],
        spec: [{required: true, message: '请输入规格'}],
        gs: [{required: true, message: '请输入公式'}]
      },
      url: {
        add: "/base/erpGoodsFormulaGs/add",
        edit: "/base/erpGoodsFormulaGs/edit",
        queryById: "/base/erpGoodsFormulaGs/queryById"
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  watch:{
    'model.gs': {
      handler: function (newValue, oldValue) {
        // do something
        this.model.gs = newValue.replace(/[^\d.+*/()\[\]-]|(\[[^\]]*\])/g, '$1');
      },
      deep: true
    }
  },
  methods: {
    // handleInput(e){
    //   this.model.gs = e.target.value.replace(/[^0-9\.\+\-\*\/\(\)\[\]]|\[[^\]]*\]/g, '');
    // },
    handleBlur(event) {
      // this.cursorPosition = event.target.selectionStart;
      var elem = event.relatedTarget || event.srcElement || event.target ||event.currentTarget;
      console.log("获得的键",event)
      if(event.keyCode==8){//判断按键为backSpace键
        //
        return ;
      }
      this.cursorPosition = event.srcElement.selectionStart;
      console.log(this.cursorPosition)
    },
    insertText(text) {
      this.model.gs =
        this.model.gs.substring(0, this.cursorPosition) +
        text +
        this.model.gs.substring(this.cursorPosition);
      this.cursorPosition = this.cursorPosition + text.length
      // this.$refs.textarea.focus();
    },
    clearGs(){
      this.model.gsMaterialId = ''
      this.model.gs = ''
    },
    goodsOk(row) {
      console.log('获取的值',row)
      console.log(this.model.gsMaterialId)
      this.model.gsMaterialId += "," + row.id
      this.insertText('['+row.name + ']')
      // this.model.gs = this.model.gs + '['+row.name + ']'
    },
    fg(content) {
      // this.model.gs = this.model.gs + content
      this.insertText(content)
    },
    addPFB(){
      // this.model.gs = this.model.gs + '[配方比]';
      this.insertText('[配方比]')
    },
    selMat(){
      //选择物料
      this.$refs.selectGoodsList.add();
      this.$refs.selectGoodsList.title = "选择物料";
      this.$refs.selectGoodsList.disableSubmit = false;
    },
    getPfCode() {
      postAction('/sys/fillRule/executeRuleByCode/pfgs', {}).then(res => {
        this.model.code = res.result;
      })
    },
    add() {
      this.edit(this.modelDefault);
      this.getPfCode();
      this.model.name = this.goods.name;
      this.model.spec = this.goods.noneSpec;
      this.model.materialId =  this.goods.id;
      this.model.gsMaterialId = ''
    },
    edit(record) {
      this.model = Object.assign({}, record);
      this.visible = true;
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
  }
}
</script>